/**
 * JAVACC DEMO 1.0
 * @copy right zbxsoft company All rights reserved. 
 * @Package com.zbxsoft.platform.template.helper  
 */
package com.apache.design.template.helper;

import com.apache.cache.util.Validator;
import com.apache.design.template.FreemarkerHelper;
import com.apache.design.util.DatabaseUtils;
import com.apache.design.util.DesignEntity;
import com.apache.design.util.FileOperate;
import com.apache.info.entity.PubMetadata;
import com.apache.info.entity.PubSortInfo;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  生成配置实现类
 */
public class IbatisTempManager extends SupperTemplateManager {

	@SuppressWarnings("unchecked")
	public boolean doInvoke(DesignEntity entity) {
		boolean mark = false;
		List<PubSortInfo> list = entity.getTabs();
		String jarPath = entity.getPackPath();
		String projectName = entity.getProjectName();
		String xmlPath = entity.getFilePath();
		Connection conn = this.getConn(entity);
		try {
			createHibernateAndMyibatis(conn, list, jarPath, projectName, xmlPath);
			mark = true;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("生成配置失败", e);
		} finally {
			DatabaseUtils.getInstance().close(conn,null);
		}
		return mark;
	}

	@SuppressWarnings("rawtypes")
	private void createHibernateAndMyibatis(Connection conn,List<PubSortInfo> list, String jarPath, String projectName,
			String filePath) throws Exception {
		String xmlPath = filePath + "/" + projectName + "/src/main/resources/ibatis/sqlmaps/";
		FileOperate.getInstance().newCreateFolder(xmlPath);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("packPath", jarPath);
		for (PubSortInfo map : list) {
			List<PubMetadata> mts = DatabaseUtils.getInstance().getTableColumns(conn, map.getInfoTableName());
			if(!Validator.isEmpty(mts)){
				StringBuilder sb = new StringBuilder();
				for(PubMetadata pm : mts){
					if("4".equals(pm.getDataRestrict())){
						sb.append(" and "+pm.getDataShortName()+"=#{"+pm.getDataAttr()+"}");
					}
				}
				if(sb.length()>0)
				data.put("lhprimary",sb.delete(0,4).toString());
			}
			data.put("metadatas", mts);
			data.put("sort", map);
			String result = FreemarkerHelper.instance().getTemplateStr("config/ibatis/ObjNameMapper.inc", data);
			result = result.replaceAll("###", "#{");
			result = result.replace("111{", "${");
			FileOperate.getInstance().newCreateFile(xmlPath + map.getObjName() + "Mapper.xml", result);
		}
	}

}
